package cn.tedu.bzy.controller;


import cn.tedu.bzy.entity.User;
import cn.tedu.bzy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    //定义图片路径
    @Value("${dirPath}")
    private String dirPath;
    //查询个人信息
    @RequestMapping("/user/selectById")
    public User selectById(HttpSession session){
        User u = (User) session.getAttribute("user");
        return mapper.selectAllById(u.getUid());
    }

    //修改个人信息
    @RequestMapping("user/upload")
    public void uploadById(User user,  MultipartFile picFile) throws IOException {
        System.out.println("user = " + user + "picFile = " + picFile);
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;


        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");

        String datePath = format.format(new Date());

        File dirFile = new File(dirPath+datePath);

        if (!dirFile.exists()){
            dirFile.mkdirs();
        }

        String filePath = dirPath+datePath+fileName;

        picFile.transferTo(new File(filePath));

        user.setPicUrl(datePath+fileName);
        mapper.updateById(user);

    }
}
